<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <card-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="removeBatch"
          >
            删除
          </el-button>
          <el-button
            size="small"
            type="warning"
            icon="el-icon-_save"
            class="ele-btn-icon"
            @click="onExport"
          >
           导出
          </el-button>
          <!-- <el-button
            size="small"
            type="info"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="download"
          >
           实体样例下载
          </el-button> -->
        </template>



        <template v-slot:is_status="{ row }">
          <el-tag v-if="row.is_status==1" type="warning" effect="plain">待使用</el-tag>
          <el-tag v-if="row.is_status==2" type="success" effect="plain">已使用</el-tag>
        </template>
 <template v-slot:card_type="{ row }">
             <el-tag v-if="row.card_type==1" type="warning" effect="plain">合伙人购买</el-tag>
          <el-tag v-if="row.card_type==2" type="success" effect="plain">用户使用</el-tag>
        </template>
        <template v-slot:day="{ row }">
          <div v-if="row.day">会员天数：{{row.day}}</div>
          <div v-if="row.day">视频合成秒数：{{row.second_infinite == 0 ? row.second : '无限'}}</div>
          <div v-if="row.day">声音高保真次数：{{row.voice_twin_count}}</div>
           
            <div v-if="row.day">声音高保真合成字数：{{row.high_fidelity_words_number}}</div>

            <div v-if="row.day">ai文案次数：{{row.ai_copywriting_times}}</div>
            <div v-if="row.day">声音专业版次数：{{row.xunfei_sound_clone_words_number}}</div>
            <div v-if="row.day">声音专业版次数字数：{{row.xunfei_sound_generate_words_number}}</div>
             <div v-if="row.day">ai标题次数{{row.ai_title_times}}</div>
            <div v-if="row.point">充值点数：{{row.point}}</div>
        </template>

        <template v-slot:user="{ row }">
          <div class="ele-cell" v-if="row.figureUser">
            <el-avatar v-if="row.figureUser.avatar"  :src="row.figureUser.avatar" shape="square" :size="40" />
            <div class="ele-cell-content">
              <div class="ele-cell-title">{{ row.figureUser.nickname }} </div>
              <div class="ele-cell-desc">{{ row.figureUser.telphone }} </div>
            </div>
          </div>
          <span v-else>无</span>
          
        </template>

        <template v-slot:use_time="{ row }">

          <span v-if="row.use_time">{{ row.use_time }}</span>
          <span v-else>无</span>
          
        </template>





        <!-- 状态列 -->
        <template v-slot:is_display="{ row }">
          <el-switch
            :active-value="1"
            :inactive-value="2"
            v-model="row.is_display"
            @change="editStatus(row)"
          />
        </template>


        <template v-slot:sort>
          <i class="sort-handle el-icon-rank ele-text-secondary" style="cursor: move;"></i>
        </template>

        
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <!-- <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="openEdit(row)"
          >
            修改
          </el-link> -->
          <el-popconfirm
            class="ele-action"
            title="确定要删除此数据吗？"
            @confirm="remove(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <card-edit :type="type" :visible.sync="showEdit" :data="current"  @done="reload"/>
  </div>
</template>

<script>
  import CardSearch from './components/card-search';
  import CardEdit from './components/card-edit';
  import { list, remove, modify,sortChange,doDefault  } from '@/api/card';
  import Sortable from 'sortablejs';
  import { utils, writeFile } from 'xlsx';

  export default {
    name: 'Card',
    components: {
      CardSearch,
      CardEdit
    },
    data() {
      return {
        type:1,
        // 表格列配置
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'name',
            label: '名称',
            showOverflowTooltip: true,
            minWidth: 110
          },
             {
            prop: 'card_type',
            label: '卡密类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'card_type'
            
          },
          {
            prop: 'card',
            label: '卡密',
            showOverflowTooltip: true,
            minWidth: 110,
          },
          {
            prop: 'day',
            label:'套餐',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180,
            slot: 'day'
          },
        
        
          {
            prop: 'is_status',
            label: '状态',
            align: 'center',
            width: 150,
            resizable: false,
            slot: 'is_status',
            showOverflowTooltip: true
          },
          {
            prop: 'user',
            label: '使用者',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'user'
          },
          {
            prop: 'use_time',
            label: '使用时间',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'use_time'
          },
          {
            prop: 'create_time',
            label: '创建时间',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (row, column, cellValue) => {
              return this.$util.toDateString(cellValue);
            }
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            hideInSetting: true,
            showOverflowTooltip: true
          }
        ],
        // 表格选中数据
        selection: [],
        // 当前编辑数据
        current: null,
        // 是否显示编辑弹窗
        showEdit: false,
        // 是否显示分配回收员
        showCollector: false,
        //弹框名称
        id:0,
        where:{
          name:1,
          is_status:'',
          nickname:'',
        },
        exportData:[],
      };
    },
    methods: {
      onExport() {

          console.log(this.where);

          list(this.where).then((data) => {
            this.exportData = data.list;

            let array = [
              ['名称', '卡密','点数', '形象克隆次数', '声音克隆次数', '状态', '使用者', '使用时间', '创建时间']
            ];

            


            this.exportData.forEach((d, i) => {

                if(d.is_status == 1){
                  d.is_status = '未使用';
                }else if(d.is_status == 2){
                  d.is_status = '已使用';
                }

                if(!d.figureUser || typeof d.figureUser  === 'undefined' ||  typeof d.figureUser.nickname === 'undefined' || d.figureUser.nickname == null || d.figureUser.nickname=== ''){
                  d.nickname = '无';
                }else{
                  d.nickname =  d.figureUser.nickname ;
                }

                if( d.use_time  === 'undefined' || d.use_time== null || d.use_time === ''){
                  d.use_time = '无';
                }
                array.push([d.name, d.card, d.point, d.avatar_twin_count, d.voice_twin_count, d.is_status, d.nickname, d.use_time,d.create_time]);
            });
            const sheet = utils.aoa_to_sheet(array);
            // 如果需要设置列宽可以这样写
            sheet["!cols"] = [
                { wch: 20 },
                { wch: 30 },
                { wch: 30 },
                { wch: 10 },
                { wch: 20 },
                { wch: 20 },
                { wch: 20 },
                { wch: 20 }
            ];
            writeFile(
                {
                    SheetNames: ['Sheet1'],
                    Sheets: {
                        Sheet1: sheet
                    }
                },
                this.type == 1 ?  '会员卡密.xlsx' :'点数卡密.xlsx'
            );

          }).catch((e) => {
            this.$message.error(e.message);
          });


          
      },
      rowDrop() {
        const tbody = document.querySelector('.el-table__body-wrapper tbody')
        const _this = this
        Sortable.create(tbody, {
          forceFallback: true,
          dragClass: 'drag',
          delay:100,
          animation: 1000,
          onEnd({ newIndex, oldIndex }) {
            console.log(newIndex);
            console.log(oldIndex);
            //更换表格数据 后续拖动坐标才会正确
            let data = _this.$refs.table.getData();
             
            let nid = data[newIndex].id;
            let oid = data[oldIndex].id;

            console.log(nid);
            console.log(oid);
            
            const currRow = data.splice(oldIndex, 1)[0];
            data.splice(newIndex, 0, currRow);

            sortChange(data).then((msg) => {
              
            }).catch((e) => {
              _this.$refs.table.reload();
            });
            //去数据库更换排序
            console.log(_this.$refs.table.getData());
          }
        })
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        where = where ? where : {};
        where.type = this.type;
        this.where = where;
        return list({ ...where, ...order, page, limit });
      },
      /* 刷新表格 */
      reload(where) {
        where = where ? where : {};
        where.type = this.type;
        this.where = where;
        this.$refs.table.reload({ page: 1, where: where });
      },
      /* 打开编辑弹窗 */
      openEdit(row) {
        this.current = row;
        this.showEdit = true;
      },
      /* 删除 */
      remove(row) {
        const loading = this.$loading({ lock: true });
        remove(row.id).then((msg) => {
          loading.close();
          this.$message.success(msg);
          this.reload();
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
      },

      /* 一键默认 */
      doDefault() {
        
        this.$confirm('请谨慎使用该功能，一旦使用则会变成系统默认内容。确定一键默认？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({ lock: true });
          doDefault().then((msg) => {
            loading.close();
            this.$message.success(msg);
            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
        }).catch(() => {});
      },
      
      /* 批量删除 */
      removeBatch() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$confirm('确定要删除选中的数据吗?', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({ lock: true });
          remove(this.selection.map((d) => d.id))
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        }).catch(() => {});
      },
      
      /* 更改状态 */
      editStatus(row) {
        const loading = this.$loading({ lock: true });
        modify({id:row.id,field:'is_display',value: row.is_display})
          .then((msg) => {
            loading.close();
            this.$message.success(msg);
          })
          .catch((e) => {
            loading.close();
            row.status = !row.status ? 1 : 0;
            this.$message.error(e.message);
          });
      }
    },mounted() {
      this.rowDrop()
      //this.columnDrop()
    },
    watch: {
      $route: {
        handler(route) {
          this.type = route.query.type;
        },
        immediate: true
      },
      type(){
        this.reload();
      }
    },
  };
</script>

<style lang="scss" scoped>

  .drag {
    background: #000 !important;
    background-image: linear-gradient(#333, #999) !important;
  }

  .ele-cell-content {
   
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

</style>